const app = getApp()
Page({
  data: {
    screenHeight: 0,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    reboot_ble_bool: false,
    devices: [],
    connected: false,
    chs: [],
    glassId: "",
    searching: false,
    devicePrefix:"WH-BLE",
    deviceFilter:false,
    deviceDiscoveryDuration:60000,  //搜索时长1分钟

  },
  //事件处理函数
  connectComplete() {
    //连接完成 要保存参数 跳转界面
  

    var connectedDeviceInfo={
     deviceId: this._deviceId,
     serviceId:this._serviceId,
     characteristicId:this._characteristicId,
    };
    app.globalData.connected=true;
    app.globalData.connectedDeviceInfo=connectedDeviceInfo;
    app.globalData.nativeDeviceId=this._deviceId;

    //本地存储 设备ID
    //wx.setStorageSync('nativeDeviceId', app.globalData.nativeDeviceId);

    var pages = getCurrentPages(); // 当前页面
    var beforePage = pages[pages.length - 2]; // 前一个页面
    /*wx.navigateBack({
      success:function(){
        beforePage.onLoad();
      }
    });
    */
    wx.redirectTo({
      url: '/pages/device/index',
    });
    
    console.log("连接设备完成，跳转页面");
  },

  /**
   * 开始动作
   */
  startProcess() {
    console.log("start process");
    this.openBluetoothAdapter();
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          console.log('discovering');
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          console.log('available');
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },

  /**
   * 开始发现蓝牙设备
   */
  startBluetoothDevicesDiscovery:function() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true;
    if (app.globalData.nativeDeviceId == "") {
      //暂未绑定设备
      wx.showLoading({
        title: '准备绑定设备',
        mask: true
      })
    }
    this.setData({
      searching: true
    });
    wx.showLoading({
      title: '正在搜索设备',
      mask: true
    });
    var _this=this;
      wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: (res) => {
          console.log('startBluetoothDevicesDiscovery success', res);
          //注册蓝牙设备发现事件
          this.onBluetoothDeviceFound();
          //设置蓝牙设备发现结束事件
          setTimeout(function(){
            console.log("device discovery timer done");
            _this.stopBleDeviceDiscovery();
          },this.data.deviceDiscoveryDuration);
        },
      })
  },

  /**
   * 停止蓝牙发现设备
   */
  stopBleDeviceDiscovery() {
    console.log("stop device discovery");
    
    //清除所有提示框
    wx.hideLoading();
    wx.stopBluetoothDevicesDiscovery();
    this.setData({searching:false});
  },

  /**
   * 找到设备 回调函数
   * Android 6.0以上需要手机打开定位服务 否则搜不到设备
   */  
  onBluetoothDeviceFound:function() {
    
    wx.onBluetoothDeviceFound((res) => {
     console.log("onBluetoothDeviceFound callback");
      console.log("device number:"+res.devices.length);
     // console.log(res);
      //会不断出现新设备 可能需要通过rssi强度过滤
      res.devices.forEach(device => {

        //有的设备没有设备名
        if (!device.name || !device.localName) {
         // console.log("device name or localName is null");
          return;
        }
        //过滤其他设备
        if (this.data.deviceFilter&&device.name.indexOf(this.data.devicePrefix) !== 0){
          return;
        }
        
        const foundDevices = this.data.devices;
        wx.hideLoading();

        const idx = this.inArray(foundDevices, 'deviceId', device.deviceId);
        const data = {};
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device;
        } else {
          data[`devices[${idx}]`] = device;
        }
        this.setData(data);

      })
    });
    //console.log("device found callbackset");
  },

  /**
   * 开始创建 与对应设备的连接
   */
  createBLEConnectionDirect(name, deviceId) {
    console.log("开始连接" + name + ":" + deviceId);
    this.stopBleDeviceDiscovery();
    wx.showLoading({
      title: '正在连接',
      mask: true
    });
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        });
        this.getBLEDeviceServices(deviceId);

      }
    });
  },

  /**
   * 对应设备点击事件
   */
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset;

    const deviceId = ds.deviceId;
    const name = ds.name;

    console.log("开始连接" + name + ":" + deviceId);

    
    var deviceInfo={id:deviceId,name:name};
    app.globalData.connectedDevice=deviceInfo;
   
    this.stopBleDeviceDiscovery();
    
    wx.showLoading({
      title: '正在连接',
      mask: true
    });
    var _this=this;
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        //this.getBLEDeviceServices(deviceId)
        _this.connectComplete();
      }
    });
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    });
    app.globalData.connected=false;
  },
  /**
   * 获取设备 service
   */
  getBLEDeviceServices(deviceId) {
    console.log("获取设备Services");
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log(res);
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  /**
   * 获取设备特征值
   */
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    console.log("获取设备Characteristics");
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {

          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          console.log("!!!:" + item.uuid);
          if (item.properties.write) {
            this.setData({
              canWrite: true,
            })

            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            console.log("订阅设备:" + deviceId + ":" + serviceId + ":" + item.uuid);

            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
              complete: (res) => {
                wx.showToast({
                  title: '连接成功',
                  complete: () => {

                    //显示连接成功 跳转界面
                    this.connectComplete();
                  }
                })
                console.log("订阅结束:" + res.errCode);
              }
            })
          }
          console.log("*********");
          console.log(this._deviceId);
          console.log(this._serviceId);
          console.log(this._characteristicId);
          console.log("*********");
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    });

    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      console.log("监听到数据变化");
     /* const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      data[`chs[${this.data.chs.length}]`] = {
        uuid: characteristic.characteristicId,
        value: ab2hex(characteristic.value)
      }
      
      var receiveText = buf2string(characteristic.value)
      console.log("收到数据:" + receiveText);
      this.setData(data)
      */
    })
  },
  /**
   * 向蓝牙设备发送一个数据
   */
  writeBLECharacteristicValue() {
   
    console.log("发送数据");
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._deviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  /**
   * 断开蓝牙
   */
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  /**
   * 开启蓝牙适配器
   */
  openBluetoothAdapter() {
    wx.showLoading({
      title: '正在开启蓝牙',
      mask: true
    })
    wx.openBluetoothAdapter({
      success: (res) => {
        wx.showLoading({
          title: '蓝牙开启成功',
          mask: true
        })
        app.globalData.reboot_ble_bool = false;
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery();
      },
      fail: (res) => {
        console.error("ble adapter open fail");
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '请确保设备蓝牙功能已打开，且允许微信连接蓝牙,部分机型需要授予微信定位权限',
          showCancel: false,
          complete: () => {
            app.globalData.reboot_ble_bool = true;
            //todo
            wx.navigateTo({
               url: '/pages/index/index',
            });
          }
        });

      }
    })
  },



  buf2string: (buffer) => {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    var str = ''
    for (var i = 0; i < arr.length; i++) {
      str += String.fromCharCode(arr[i])
    }
    return str
  },
  inArray: (arr, key, val) => {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i][key] === val) {
        return i;
      }
    }
    return -1;
  },
  // ArrayBuffer转16进度字符串示例
  ab2hex: (buffer) => {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },

  /**
   * 是否目标类型设备
   */
  isTargetDevice: function(name)  {
    var that=this;
  
    if (name.indexOf(that.data.devicePrefix) === 0) {
      return true;
    } else {
      return false;
    }
  },
  onLoad: function () {
    //获取屏幕高度 
    wx.getSystemInfo({
      success: (res) => {
        let screenheight = res.screenHeight;
        this.setData({
          screenHeight: screenheight
        });
        this.startProcess();
      },
    })
  },
  deviceDiscover:function(){
    this.startBluetoothDevicesDiscovery();
  }

})
